package com.ct.musicserver.service.impl;

import com.ct.musicserver.common.errorcode.ServiceErrorCodeConstants;
import com.ct.musicserver.common.exception.ServiceException;
import com.ct.musicserver.controller.param.UserLoginParam;
import com.ct.musicserver.dao.dataobject.UserDO;
import com.ct.musicserver.dao.mapper.UserMapper;
import com.ct.musicserver.service.UserService;
import com.ct.musicserver.service.dto.UserLoginDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserLoginDTO login(UserLoginParam param) {
        UserDO userDO = userMapper.selectByName(param.getUsername());
        if (null == userDO) {
            throw new ServiceException(ServiceErrorCodeConstants.USER_INFO_EMPTY);
        }
        boolean flag = bCryptPasswordEncoder.matches(param.getPassword(), userDO.getPassword());
        if (!flag) {
            throw new ServiceException(ServiceErrorCodeConstants.PASSWORD_ERROR);
        }
        UserLoginDTO userLoginDTO = new UserLoginDTO();
        userLoginDTO.setId(userDO.getId());
        userLoginDTO.setUsername(userDO.getUsername());
        userLoginDTO.setPassword(userDO.getPassword());

        return userLoginDTO;
    }
}
